package allenja.cp2011.MVC;

import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;

public class ChatServerTests {
	Connection conn;
	Rot13EncryptDecrypt rot13Helper = new Rot13EncryptDecrypt();

	@Test // Test the port number
	public void testSetPortNumber() {
		int expected = RunChatMVC.portNumber;
		assertEquals(expected, 49696);
	}

	@Test // Test the Derby embedded database driver
	public void testDerbyDriver() {
		
		try {
			assertNotNull(Class.forName("org.apache.derby.jdbc.EmbeddedDriver"));
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();			
		}
	}
	
	@Test // Test the database connection
	public void testDerbyConnection() {
		// Using the Java Input/Output temp directory for testing
		String tempPath = System.getProperty("java.io.tmpdir");
		String connString = "jdbc:derby:" + tempPath + "ChatServerDB;create=true";

		try {
			conn = DriverManager.getConnection(connString);
			assertNotNull(conn);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}		
	}
	
	@Test // Test the database metadata
	public void testDerbyMetadata() {
		// Using the Java Input/Output temp directory for testing
		String tempPath = System.getProperty("java.io.tmpdir");
		// Create a connection to the database for accessing the metadata
		String connString = "jdbc:derby:" + tempPath + "ChatServerDB;create=true";
		DatabaseMetaData dbMetaData;
		
		try {
			conn = DriverManager.getConnection(connString);
			dbMetaData = conn.getMetaData();
			ResultSet metadataResultSet = dbMetaData.getTables(null, null, "CHATSERVERUSERS", null);
			assertNotNull(metadataResultSet);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}		
	}
	
	@Test // Test ROT13
	public void testRot13() {
		String plainText = "Hello world!";
		String cipherText = "Uryyb jbeyq!";
		
		assertEquals(cipherText, rot13Helper.convert(plainText));
	}
}
